package com.example.leadnewsbehavor.web.v1;

import com.qf.qfleadnewscommons.mvc.ThreadLocalUtils;
import com.qf.qfleadnewsmodel.behavior.dtos.BehaviorDto;
import com.qf.qfleadnewsmodel.commons.consts.RedisConst;
import com.qf.qfleadnewsmodel.commons.dtos.ResponseResult;
import com.qf.qfleadnewsmodel.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class BehaviorController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/read_behavior")
    public ResponseResult read(@RequestBody BehaviorDto behaviorDto){
        //记录当前文章的阅读数量 -- incr
        String key = RedisConst.ARTICLE_READ_PREFIX + behaviorDto.getArticleId();
        redisTemplate.opsForValue().increment(key);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @PostMapping("/likes_behavior")
    public ResponseResult like(@RequestBody BehaviorDto behaviorDto){
        //记录当前用户是否对这篇文章点赞

        Integer operation = behaviorDto.getOperation();
        String key = RedisConst.ARTICLE_LIKE_PREFIX + behaviorDto.getArticleId();
        //利用当前点赞用户的id作为文章位图的偏移量
        long offset = ThreadLocalUtils.getUid();
        boolean value = false;
        if(operation == 0){
            //0-点赞  setBit
            value = true;
        }else{
            //1-取消点赞 setBit
            value = false;
        }
        redisTemplate.opsForValue().setBit(key,offset,value);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @PostMapping("/un_likes_behavior")
    public ResponseResult unlike(@RequestBody BehaviorDto behaviorDto){
        //记录当前用户是否对这篇文章不喜欢操作

        Integer operation = behaviorDto.getType();
        String key = RedisConst.ARTICLE_UNLIKE_PREFIX + behaviorDto.getArticleId();
        //利用当前点赞用户的id作为文章位图的偏移量
        long offset = ThreadLocalUtils.getUid();
        boolean value = false;
        if(operation == 0){
            //0-点赞  setBit
            value = true;
        }else{
            //1-取消点赞 setBit
            value = false;
        }
        redisTemplate.opsForValue().setBit(key,offset,value);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }
}
